package mbp.gui.panels;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;
import java.awt.Color;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.table.DefaultTableModel;
import javax.swing.JComboBox;

import mbp.base.DateString;
import mbp.base.ServiceType;
import mbp.base.Settings;
import mbp.core.CounterOffer;
import mbp.core.Intention;
import mbp.core.Offer;
import mbp.core.ServiceTypeBuilder;
import mbp.gui.frames.COfferEditor;
import mbp.gui.frames.MbpManagerGui;
import mbp.gui.frames.OfferEditor;

import javax.swing.JScrollPane;
import javax.swing.JTable;

public class ServiceServerGui extends JPanel implements ActionListener
{
	private MbpManagerGui mbpManagerGui;
	private JTextField txtAgentName;
	private JComboBox cmbTypesXml, cmbIntentions;
	private JButton btnCreate, btnSet, btnDetails;
	private HashMap<String, Intention> intentionsStore;
	private Intention actualIntention;
	private int itemCounter;
	private JTable table;
	private DefaultTableModel modelInt;
	private JButton btnSend;
	private JButton btnCouteroffer, btnAccept, btnReject;
	private JPanel panel_3;
	private Offer offer;
	private JTextField txtOfferType;
	private JTextField txtCdate;
	private JTextField txtVdate;
	private JTextField txtMaxTerm;

	/**
	 * Create the panel.
	 */
	public ServiceServerGui(MbpManagerGui mbpManagerGui) 
	{
		this.mbpManagerGui = mbpManagerGui;
		intentionsStore = new HashMap<String, Intention>();
		itemCounter = 0;
		setLayout(null);
		
		JPanel panel_0 = new JPanel();
		panel_0.setLayout(null);
		panel_0.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Agent ServiceServer", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_0.setBounds(10, 11, 141, 70);
		add(panel_0);
		
		txtAgentName = new JTextField();
		txtAgentName.setColumns(10);
		txtAgentName.setBounds(10, 39, 120, 20);
		panel_0.add(txtAgentName);
		
		JLabel label = new JLabel("Agent name");
		label.setBounds(10, 24, 80, 14);
		panel_0.add(label);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Intention", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(161, 11, 426, 159);
		add(panel_1);
		panel_1.setLayout(null);
		
		cmbIntentions = new JComboBox();
		cmbIntentions.setBounds(10, 26, 120, 20);
		panel_1.add(cmbIntentions);
		
		btnSet = new JButton("Set");
		btnSet.setBounds(140, 25, 89, 23);
		panel_1.add(btnSet);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 87, 400, 61);
		panel_1.add(scrollPane);
		
		modelInt = new DefaultTableModel();
		modelInt.addColumn("Resource");
		modelInt.addColumn("Condition");
		modelInt.addColumn("Quantity");
		table = new JTable(modelInt);
		table.setFillsViewportHeight(true);
		scrollPane.setViewportView(table);
		
		btnSend = new JButton("Send");
		btnSend.setBounds(239, 25, 89, 23);
		panel_1.add(btnSend);
		
		txtMaxTerm = new JTextField();
		txtMaxTerm.setBounds(10, 67, 86, 20);
		panel_1.add(txtMaxTerm);
		txtMaxTerm.setColumns(10);
		
		JLabel lblMaxRealizeTerm = new JLabel("Max realize term");
		lblMaxRealizeTerm.setBounds(99, 70, 100, 14);
		panel_1.add(lblMaxRealizeTerm);
		btnSet.addActionListener(this);
		btnSend.addActionListener(this);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new TitledBorder(null, "Intention type", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_2.setBounds(10, 81, 141, 89);
		add(panel_2);
		panel_2.setLayout(null);
		
		cmbTypesXml = new JComboBox();
		cmbTypesXml.setBounds(10, 25, 120, 20);
		panel_2.add(cmbTypesXml);
		
		btnCreate = new JButton("Create");
		btnCreate.setBounds(10, 56, 89, 23);
		panel_2.add(btnCreate);
		
		btnCreate.addActionListener(this);
		
		panel_3 = new JPanel();
		panel_3.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Recieved offer", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 70, 213)));
		panel_3.setBounds(10, 181, 577, 110);
		add(panel_3);
		panel_3.setLayout(null);
		
		btnDetails = new JButton("Details");
		btnDetails.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnDetails.setBounds(10, 67, 89, 23);
		panel_3.add(btnDetails);
		btnDetails.addActionListener(this);
		
		txtOfferType = new JTextField();
		txtOfferType.setEditable(false);
		txtOfferType.setBounds(10, 36, 89, 20);
		panel_3.add(txtOfferType);
		txtOfferType.setColumns(10);
		
		JLabel lblServiceType = new JLabel("Service type");
		lblServiceType.setBounds(10, 21, 86, 14);
		panel_3.add(lblServiceType);
		
		txtCdate = new JTextField();
		txtCdate.setEditable(false);
		txtCdate.setBounds(109, 36, 150, 20);
		panel_3.add(txtCdate);
		txtCdate.setColumns(10);
		
		JLabel lblOfferCreationDate = new JLabel("Offer creation date");
		lblOfferCreationDate.setBounds(109, 21, 150, 14);
		panel_3.add(lblOfferCreationDate);
		
		txtVdate = new JTextField();
		txtVdate.setEditable(false);
		txtVdate.setBounds(269, 36, 150, 20);
		panel_3.add(txtVdate);
		txtVdate.setColumns(10);
		
		JLabel lblOfferExpirationDate = new JLabel("Offer expiration date");
		lblOfferExpirationDate.setBounds(269, 21, 150, 14);
		panel_3.add(lblOfferExpirationDate);
		
		btnAccept = new JButton("Accept");
		btnAccept.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnAccept.setBounds(109, 67, 91, 23);
		panel_3.add(btnAccept);
		btnAccept.addActionListener(this);
		
		btnReject = new JButton("Reject");
		btnReject.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnReject.setBounds(210, 67, 91, 23);
		panel_3.add(btnReject);
		btnReject.addActionListener(this);
		
		btnCouteroffer = new JButton("Couteroffer");
		btnCouteroffer.setFont(new Font("Dialog", Font.PLAIN, 11));
		btnCouteroffer.setBounds(311, 67, 91, 23);
		panel_3.add(btnCouteroffer);
		btnCouteroffer.addActionListener(this);
		
		cmbIntentions.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) {
				int index = cmbIntentions.getSelectedIndex();
				if(index == -1)
				{
					return;
				}
				String key = (String)cmbIntentions.getItemAt(index);
				loadIntention(intentionsStore.get(key));
				// TODO Auto-generated method stub
				
			}
		});

	}
	
	public void LoadServiceTypeList(List<String> types)
	{
		Iterator<String> it = types.iterator();
		
		while(it.hasNext())
		{
			String type = it.next();
			cmbTypesXml.addItem(type);
		}
	}
	
	/**
	 * Dodaje nowy obiekt Intention do kolekcji
	 * @param intention
	 */
	public void addIntention(Intention intention)
	{
		intention.setClientName(mbpManagerGui.myAgent.getLocalName());
		String name = intention.getServiceType().getServiceTypeName() + " [" + itemCounter++ + "]";
		intentionsStore.put(name, intention);
		cmbIntentions.addItem(name);
		cmbIntentions.setSelectedItem(name);
	}
	
	public void clearRecievedOffer()
	{
		this.offer = null;
		txtOfferType.setText("");
		txtCdate.setText("");
		txtVdate.setText("");
	}
	
	public void loadIntention(Intention intention)
	{
		int rowsCount = 0;
		
		txtMaxTerm.setText(intention.getRealizeMaxTU().toString());
		
		/**
		 * Wyczyszczenie tabeli
		 */
		for( int i = modelInt.getRowCount() - 1; i >= 0; i-- )
		{
		    modelInt.removeRow(i);
		}
		
		for(int i = 0; i<intention.getResourcesOut().size(); i++)
		{
			String type = intention.getResourcesOut().get(i).getType().getResourceTypeName();
			String cnd = intention.getResourcesOut().get(i).getCondition();
			String quantity = intention.getResourcesOut().get(i).getQuantity().toString();
			
			modelInt.insertRow(rowsCount, new Object[]{type,  cnd, quantity});
			rowsCount++;
		}
		
		actualIntention = intention;
	}
	
	public void loadRecievedOffer(Offer ofr)
	{
		this.offer = ofr;
		txtOfferType.setText(ofr.getType().getServiceTypeName());
		txtCdate.setText(DateString.DateToStr(ofr.getOfferCreateDate()));
		txtVdate.setText(DateString.DateToStr(ofr.getOfferValidityDate()));
	}
	
	public void setIntention(Intention intention)
	{
		intention.setRealizeMaxTU(Integer.parseInt(txtMaxTerm.getText()));
		for(int i = 0; i<modelInt.getRowCount(); i++)
		{
			String cnd = (String)modelInt.getValueAt(i, 1);
			Integer quantity = Integer.parseInt( (String)modelInt.getValueAt(i, 2) );
			intention.getResourcesOut().get(i).setCondition(cnd);
			intention.getResourcesOut().get(i).setQuantity(quantity);
		}
	}
	
	public ArrayList getIntentoinsList()
	{
		ArrayList<Intention> intentionsList = new ArrayList<Intention>(intentionsStore.values());
		return intentionsList;
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource() == btnCreate)
		{
			ServiceTypeBuilder stb = new ServiceTypeBuilder("");
			ServiceType type = stb.GetServiceType((String)cmbTypesXml.getSelectedItem());
			
			Intention intention = new Intention(type);
			//intention.setClientName(mbpManagerGui.myAgent.getLocalName());
			addIntention(intention);
		}
		
		if(e.getSource() == btnSet)
		{
			if(actualIntention != null)
			{
				setIntention(actualIntention);
			}
		}
		
		if(e.getSource() == btnSend)
		{
			clearRecievedOffer();
			actualIntention.setServerName(txtAgentName.getText());
			actualIntention.setAgentName(Settings.managerName);
			actualIntention.setClientName(Settings.managerName);
			mbpManagerGui.myAgent.SendIntention(actualIntention);
		}
		
		if(e.getSource() == btnDetails)
		{
			if(this.offer == null)
			{
				JOptionPane.showMessageDialog(null, "No offer recieved !!!", "ERROR", JOptionPane.ERROR_MESSAGE);
				return;
			}		
			OfferEditor offerEditor = new OfferEditor(this.offer);
			offerEditor.setVisible(true);
		}
		
		if(e.getSource() == btnAccept)
		{
			if(this.offer == null)
			{
				JOptionPane.showMessageDialog(null, "No offer recieved !!!", "ERROR", JOptionPane.ERROR_MESSAGE);
				return;
			}
			//JOptionPane.showMessageDialog(null, "Not implemented yet", "WARNING", JOptionPane.WARNING_MESSAGE);
			mbpManagerGui.myAgent.SendAcceptOffer(offer, txtAgentName.getText());
		}
		
		if(e.getSource() == btnReject)
		{
			if(this.offer == null)
			{
				JOptionPane.showMessageDialog(null, "No offer recieved !!!", "ERROR", JOptionPane.ERROR_MESSAGE);
				return;
			}
			JOptionPane.showMessageDialog(null, "Not implemented yet", "WARNING", JOptionPane.WARNING_MESSAGE);
		}
		
		if(e.getSource() == btnCouteroffer)
		{
			if(this.offer == null)
			{
				JOptionPane.showMessageDialog(null, "No offer recieved !!!", "ERROR", JOptionPane.ERROR_MESSAGE);
				return;
			}
			
			ServiceTypeBuilder stb = new ServiceTypeBuilder("");
			CounterOffer counterOffer = new CounterOffer(stb.GetServiceType( offer.getType().getServiceTypeName()));
			counterOffer.initialize(offer);
			
			COfferEditor cofferEditor = new COfferEditor(counterOffer, mbpManagerGui.myAgent, txtAgentName.getText());
			cofferEditor.setVisible(true);
			
			clearRecievedOffer();
			
			//JOptionPane.showMessageDialog(null, "Not implemented yet", "WARNING", JOptionPane.WARNING_MESSAGE);
		}
		
	}
}
